package com.locationtracker.plus.ui.fragment.web

import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.OnBackPressedCallback
import com.just.agentweb.AgentWeb
import com.locationtracker.plus.app.base.BaseFragment
import com.locationtracker.plus.app.ext.hideSoftKeyboard
import com.locationtracker.plus.databinding.FragmentWebBinding
import com.locationtracker.plus.viewmodel.state.WebViewModel
import me.hgj.jetpackmvvm.ext.nav

@Suppress("DEPRECATED_IDENTITY_EQUALS")
class WebFragment : BaseFragment<WebViewModel, FragmentWebBinding>() {

    private var mAgentWeb: AgentWeb? = null

    private var preWeb: AgentWeb.PreAgentWeb? = null

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeHeader.headerBack.setOnClickListener {
            hideSoftKeyboard(activity)
            mAgentWeb?.let { web ->
                if (web.webCreator.webView.canGoBack()) {
                    web.webCreator.webView.goBack()
                } else {
                    nav().navigateUp()
                }
            }
        }
        setHasOptionsMenu(true)
        arguments?.run {
            //点击收藏网址列表进来的
            getString("url")?.let { mViewModel.url = it }
        }
        preWeb = AgentWeb.with(this)
            .setAgentWebParent(mDatabind.webcontent, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .createAgentWeb()
            .ready()
    }

    override fun lazyLoadData() {
        //加载网页
        mAgentWeb = preWeb?.go(mViewModel.url)
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    mAgentWeb?.let { web ->
                        if (web.webCreator.webView.canGoBack()) {
                            web.webCreator.webView.goBack()
                        } else {
                            nav().navigateUp()
                        }
                    }
                }
            })
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb?.webLifeCycle?.onDestroy()
//        mActivity.setSupportActionBar(null)
        super.onDestroy()
    }

}